package com.bear.pk.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.bear.pk.controller.req.LoginRequest;
import com.bear.pk.controller.req.SignUpRequest;
import com.bear.pk.controller.res.ApiResponse;
import com.bear.pk.controller.res.JwtAuthenticationResponse;
import com.bear.pk.entity.RoleName;
import com.bear.pk.entity.Roles;
import com.bear.pk.entity.UserRoles;
import com.bear.pk.entity.Users;
import com.bear.pk.handler.JwtTokenProvider;
import com.bear.pk.service.IRolesService;
import com.bear.pk.service.IUserRolesService;
import com.bear.pk.service.IUsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import javax.validation.Valid;
import java.net.URI;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Autowired
    AuthenticationManager authenticationManager;

    @Autowired
    PasswordEncoder passwordEncoder;

    @Autowired
    JwtTokenProvider tokenProvider;

    @Autowired
    private IUsersService usersService;

    @Autowired
    private IRolesService rolesService;

    @Autowired
    private IUserRolesService userRolesService;

    @PostMapping("/signin")
    public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginRequest loginRequest) {

        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(
                        loginRequest.getUsernameOrEmail(),
                        loginRequest.getPassword()
                )
        );

        SecurityContextHolder.getContext().setAuthentication(authentication);

        String jwt = tokenProvider.generateToken(authentication);
        return ResponseEntity.ok(new JwtAuthenticationResponse(jwt));
    }

    @PostMapping("/signup")
    public ResponseEntity<?> registerUser(@Valid @RequestBody SignUpRequest signUpRequest) {
        if (usersService.exists(Wrappers.<Users>lambdaQuery().eq(Users::getUsername, signUpRequest.getUsername()))) {
            return new ResponseEntity(new ApiResponse(false, "Username is already taken!"), HttpStatus.BAD_REQUEST);
        }

        if (usersService.exists(Wrappers.<Users>lambdaQuery().eq(Users::getEmail, signUpRequest.getEmail()))) {
            return new ResponseEntity(new ApiResponse(false, "Email Address already in use!"), HttpStatus.BAD_REQUEST);
        }

        Users user = new Users();
        user.setName(signUpRequest.getName());
        user.setUsername(signUpRequest.getUsername());
        user.setEmail(signUpRequest.getEmail());
        user.setPassword(signUpRequest.getPassword());
        user.setPassword(passwordEncoder.encode(user.getPassword()));

        Set<String> strRoles = signUpRequest.getRoles();
        List<Roles> roles = new ArrayList<>();

        if (strRoles == null) {
            Roles userRole = Optional.ofNullable(rolesService.getOne(Wrappers.<Roles>lambdaQuery().eq(Roles::getName, RoleName.ROLE_USER)))
                    .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
            roles.add(userRole);
        } else {
            strRoles.forEach(role -> {
                switch (role) {
                    case "admin":
                        Roles adminRole = Optional.ofNullable(rolesService.getOne(Wrappers.<Roles>lambdaQuery().eq(Roles::getName, RoleName.ROLE_ADMIN)))
                                .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
                        roles.add(adminRole);

                        break;
                    case "mod":
                        Roles modRole = Optional.ofNullable(rolesService.getOne(Wrappers.<Roles>lambdaQuery().eq(Roles::getName, RoleName.ROLE_MODERATOR)))
                                .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
                        roles.add(modRole);

                        break;
                    default:
                        Roles userRole = Optional.ofNullable(rolesService.getOne(Wrappers.<Roles>lambdaQuery().eq(Roles::getName, RoleName.ROLE_USER)))
                                .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
                        roles.add(userRole);
                }
            });
        }

        user.setRoles(roles);

        usersService.save(user);

        List<UserRoles> userRolesList = user.getRoles().stream().map(e -> {
            UserRoles userRoles = new UserRoles();
            userRoles.setRoleId(e.getId());
            userRoles.setUserId(user.getId());
            return userRoles;
        }).collect(Collectors.toList());
        userRolesService.saveBatch(userRolesList);

        URI location = ServletUriComponentsBuilder
                .fromCurrentContextPath().path("/users/{username}")
                .buildAndExpand(user.getUsername()).toUri();

        return ResponseEntity.created(location).body(new ApiResponse(true, "User registered successfully"));
    }
}